package com.horay.springbootdemo.transcation.template;

import com.horay.springbootdemo.common.model.Foo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * 服务启动类
 *
 * @author heyingcheng
 * @date 2019/11/6 22:12
 */
@Slf4j
@SpringBootApplication
public class TransactionTemplateApplication implements CommandLineRunner {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private TransactionTemplate transcationTemplate;

    public static void main(String[] args) {
        SpringApplication.run(TransactionTemplateApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        log.info("COUNT BEFORE TRANSACTION:[{}]", count());

        transcationTemplate.execute((TransactionCallback) transactionStatus -> {
            jdbcTemplate.update(Foo.INSERT_SQL, "AAAAAA");
            log.info("COUNT IN TRANSACTION:[{}]", count());
            transactionStatus.setRollbackOnly();
            return null;
        });

        log.info("COUNT AFTER TRANSACTION:[{}]", count());
    }

    public long count() {
        return jdbcTemplate.queryForObject(Foo.SELECT_COUNT_SQL, Long.class);
    }

}
